package hn.sigit.dao;


import java.io.Serializable;

import javax.naming.InitialContext;
import javax.naming.NamingException;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jboss.seam.Component;


public abstract class SigitDAO<E> implements Serializable {
	private static final long serialVersionUID = -7640581780642087885L;
	
	protected static final String COMMONS_DB = "commonsDatabase";
	
	protected SigitDAO() {	
	}
	
	protected static Session getSession() {
		return getSession(COMMONS_DB);
	}
	
	protected static Session getSession(String name) {
		Session session = null;
		
		try {
			session = (Session)Component.getInstance(name);
		}
		catch (Exception e) {
			try {
				InitialContext ic;
				ic = new InitialContext();
				SessionFactory sf = (SessionFactory) ic.lookup("java:/SessionFactory");
				session = sf.openSession();
			} catch (NamingException ne) {
				// TODO Auto-generated catch block
				ne.printStackTrace();
			}
		}
		
		return session;
	}
	
	public static <E> E create(Class<E> type) {
		try {
			return type.newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static <E> void save(E ormEntity) {
		Session commonsDatabase = (Session)Component.getInstance(COMMONS_DB);
		commonsDatabase.saveOrUpdate(ormEntity);
	}
	
	public static <E> void delete(E ormEntity) {
		Session commonsDatabase = (Session)Component.getInstance(COMMONS_DB);
		commonsDatabase.delete(ormEntity);
	}
	
	public static <E> void evict(E ormEntity) {
		Session commonsDatabase = (Session)Component.getInstance(COMMONS_DB);
		commonsDatabase.evict(ormEntity);
	}
	
	public static void clear() {
		Session commonsDatabase = (Session)Component.getInstance(COMMONS_DB);
		commonsDatabase.clear();
	}
	
	public static void flush() {
		Session commonsDatabase = (Session)Component.getInstance(COMMONS_DB);
		commonsDatabase.flush();
	}

	//protected static Session commonsDatabase;
	
	/*
	public SigitDAO() {
		commonsDatabase = (Session)Component.getInstance("commonsDatabase");
	}
	public SigitDAO(Session s) {
		commonsDatabase = s;
	}
	*/
}
